package solutions.leetcode.normal;

import solutions.lib.BaseSolution;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author lizhidong
 * <a href="https://leetcode-cn.com/problems/fraction-to-recurring-decimal/">166. 分数到小数</a>
 */
public class Solution166 extends BaseSolution {

    public String fractionToDecimal(int n, int d) {
        long numerator = n;
        long denominator = d;
        int fuhao = numerator >= 0 ? 1 : -1;
        fuhao *= denominator > 0 ? 1 : -1;
        numerator = Math.abs(numerator);
        denominator = Math.abs(denominator);

        StringBuilder rst = new StringBuilder();
        if (numerator == denominator) {
            rst.append("1");
        } else if (numerator < denominator){
            rst.append("0");
        } else {
            long tr = numerator / denominator;
            rst.append(tr);
        }
        numerator %= denominator;
        if (numerator > 0) {
            rst.append(".");
        }
        LinkedHashMap<Long, Long> map = new LinkedHashMap<>();
        int ind = -1;
        while (numerator != 0) {
            numerator *= 10;
            if (map.containsKey(numerator)) {
                ind = 0;
                for (Long key : map.keySet()) {
                    if (key == numerator) {
                        break;
                    } else {
                        ind++;
                    }
                }
                break;
            } else {
                map.put(numerator, numerator / denominator);
                numerator %= denominator;
            }
        }
        boolean needAppend = ind >= 0;
        for (Map.Entry<Long, Long> entry : map.entrySet()) {
            if (ind == 0) {
                rst.append("(");
            }
            ind--;
            rst.append(entry.getValue());
        }

        return (fuhao == -1 ? "-" : "") + rst + (needAppend ? ")" : "");
    }

    public static void main(String[] args) {
        Solution166 solution = new Solution166();
        System.out.println(solution.fractionToDecimal(1, 3));
    }
}